<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="org.example.demo1.Entity.*" %>
<%@ page import="org.example.demo1.DAO.*" %>
<%@ page import="org.example.demo1.utils.MybatisUtils" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="java.util.*" %>

<%
    // 获取URL参数
    String novelIdStr = request.getParameter("novelId");
    String chapterIdStr = request.getParameter("chapterId");
    String isNewStr = request.getParameter("new");
    String volumeName = request.getParameter("volumeName");
    
    Novel novel = null;
    Chapter currentChapter = null;
    ChapterContent chapterContent = null;
    String errorMessage = null;
    boolean isNewChapter = "true".equals(isNewStr);
    
    if (novelIdStr != null) {
        try {
            int novelId = Integer.parseInt(novelIdStr);
            
            // 获取数据库连接
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            NovelDao novelDao = sqlSession.getMapper(NovelDao.class);
            
            try {
                // 获取小说信息
                novel = novelDao.getNovelById(novelId);
                
                // 如果是编辑现有章节，获取章节内容
                if (chapterIdStr != null && !isNewChapter) {
                    int chapterId = Integer.parseInt(chapterIdStr);
                    
                    // 获取章节基本信息
                    Map<String, Object> params = new HashMap<>();
                    params.put("novelId", novelId);
                    List<Chapter> chapters = novelDao.getAllChaptersByNovelId(params);
                    
                    for (Chapter chapter : chapters) {
                        if (chapter.getChapter_id().equals(chapterId)) {
                            currentChapter = chapter;
                            break;
                        }
                    }
                    
                    // 获取章节内容
                    if (currentChapter != null) {
                        chapterContent = novelDao.getChapterContentByChapterId(chapterId);
                    }
                }
                
            } finally {
                sqlSession.close();
            }
            
        } catch (NumberFormatException e) {
            errorMessage = "无效的参数格式";
        } catch (Exception e) {
            errorMessage = "加载数据时发生错误: " + e.getMessage();
        }
    } else {
        errorMessage = "缺少必要的参数";
    }
%>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>章节编辑<%= novel != null ? " - " + novel.getNovel_name() : "" %></title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        .editor-container {
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        .editor-header {
            background: white;
            border-bottom: 1px solid #dee2e6;
            padding: 1rem 0;
        }
        .editor-content {
            background: white;
            margin: 2rem 0;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        #chapterContent {
            border: none;
            resize: none;
            font-size: 16px;
            line-height: 1.8;
        }
        #chapterContent:focus {
            outline: none;
            box-shadow: none;
        }
        .toolbar {
            border-bottom: 1px solid #dee2e6;
            padding: 1rem;
        }
        .word-count {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 8px 12px;
            border-radius: 4px;
            font-size: 14px;
        }
        .error-message {
            background: white;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            color: #dc3545;
            font-size: 18px;
            margin: 2rem 0;
        }
    </style>
</head>
<body>
    <% if (errorMessage != null) { %>
        <div class="container mt-5">
            <div class="error-message">
                <h3>加载失败</h3>
                <p><%= errorMessage %></p>
                <a href="javascript:history.back()" class="btn btn-primary">返回上一页</a>
            </div>
        </div>
    <% } else { %>
        <div class="editor-container">
            <!-- 编辑器头部 -->
            <div class="editor-header">
                <div class="container-fluid">
                    <div class="row align-items-center">
                        <div class="col-md-6">
                            <button class="btn btn-outline-secondary me-2" onclick="goBack()">
                                <i class="bi bi-arrow-left"></i> 返回章节管理
                            </button>
                            <span class="text-muted" id="novelTitle">
                                <%= novel != null ? "《" + novel.getNovel_name() + "》" : "加载中..." %>
                            </span>
                        </div>
                        <div class="col-md-6 text-end">
                            <button class="btn btn-success" onclick="publishChapter()">
                                <i class="bi bi-send"></i> 发布章节
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 编辑器内容 -->
            <div class="container-fluid">
                <div class="row justify-content-center">
                    <div class="col-md-10 col-lg-8">
                        <div class="editor-content">
                            <!-- 工具栏 -->
                            <div class="toolbar">
                                <div class="mb-3">
                                    <input type="text" class="form-control form-control-lg" 
                                           id="chapterTitle" placeholder="请输入章节标题" maxlength="100"
                                           value="<%= currentChapter != null ? currentChapter.getChapter_title() : "" %>">
                                </div>
                                <div class="mb-3">
                                    <label for="volumeName" class="form-label text-muted">分卷信息</label>
                                    <input type="text" class="form-control" 
                                           id="volumeName" placeholder="请输入分卷名称（如：第一卷:初识）" maxlength="50"
                                           value="<%= volumeName != null ? volumeName : (currentChapter != null && currentChapter.getVolume_name() != null ? currentChapter.getVolume_name() : "") %>">
                                    <div class="form-text">分卷名称用于章节分组显示，可以为空</div>
                                </div>
                            </div>
                            
                            <!-- 内容编辑区 -->
                            <div class="p-4">
                                <textarea class="form-control" id="chapterContent" 
                                          rows="25" placeholder="开始您的创作..."><%= chapterContent != null ? chapterContent.getContent() : "" %></textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 字数统计 -->
        <div class="word-count" id="wordCount">字数: 0</div>

        <!-- 提示消息容器 -->
        <div id="messageContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>
    <% } %>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- 传递数据到JavaScript -->
    <script>
        window.editorData = {
            novelId: <%= novelIdStr != null ? novelIdStr : "null" %>,
            chapterId: <%= chapterIdStr != null ? chapterIdStr : "null" %>,
            isNewChapter: <%= isNewChapter %>,
            novelName: '<%= novel != null ? novel.getNovel_name().replace("'", "\\\'"): "" %>',
            volumeName: '<%= volumeName != null ? volumeName.replace("'", "\\\'"): "" %>'
        };
    </script>
    
    <!-- 章节编辑器JS -->
    <script src="${pageContext.request.contextPath}/MainPage/functionPage/chapterEditor.js"></script>
</body>
</html>